module Match
  class Search
    include Ferret
    include Ferret::Index
    include Ferret::Search

    def initialize(score = 0.5)
      @score = score
      @analyzer = RMMSeg::Ferret::Analyzer.new { |tokenizer|
        Ferret::Analysis::LowerCaseFilter.new(tokenizer)
      }
      @index = Index.new(:path => INDEX_PATH) 
      @query_parser = QueryParser.new(:analyzer => @analyzer)
      @total_hits = 0
      @results = []
    end
    
    def query(title, cat1_id, brand, nick)
      keywords = KeyExtractor.getKeys(title) 
      ret_keywords = keywords.join("|")

      #puts "\"#{ret_keywords}\""
      fql = "+cat1_id:#{cat1_id} +format_title:\"#{ret_keywords}\"" 
      fql += " +brand:#{brand}" if !brand.nil? && brand.length > 0
      #puts "#{fql}"

      _query = @query_parser.parse(fql)
      
      @total_hits = @index.search_each(_query, :limit => 500) do |doc_id, score| 
        @results << {:score => score, :total_hits => total_hits, :doc_id => doc_id, :id => @index[doc_id][:id], :format_title => @index[doc_id][:format_title], :nick => @index[doc_id][:nick], :brand => @index[doc_id][:brand], :cat1_id => @index[doc_id][:cat1_id], :cat1_name => @index[doc_id][:cat1_name], :props => @index[doc_id][:style_name], :price => @index[doc_id][:price]}
      end
       
      close
    end
    
    def total_hits()
      @total_hits ||= 0
    end
    
    def results()
      @results
    end
    
    def close
      @index.close() if @index
    end
    
  end
end
